var geocoder, map, marker = null;
var lat = 31.883853;
var lng = 117.31625;
var detail = '';
//编辑
var latitude = $("#latitude").val();
var longitude = $("#longitude").val();
var beforeDetail = $("#address").val();
if(latitude){
    var lat = latitude;
}
if(longitude){
    var lng = longitude;
}
if(beforeDetail){
    var detail = beforeDetail;
}
var searchService;
var markers = [];

var mapinit = function() {
	
	var center = new qq.maps.LatLng(lat,lng);
    map = new qq.maps.Map(document.getElementById("container"),{
        center: center,
        zoom: 13
    });
    
    //创建marker
    marker = new qq.maps.Marker({
        position: center,
        map: map
    });
     
    geocoder = new qq.maps.Geocoder();
    
    //绑定单击事件添加参数
    qq.maps.event.addListener(map, 'click', function(event) {
    	//console.log(event);
    	marker.setMap(null);
    	lat = event.latLng.getLat();
    	lng = event.latLng.getLng();
    	//根据经纬度获取地址
    	codeLatLng();
        //创建marker
        map.setCenter(event.latLng);
	    marker = new qq.maps.Marker({
	        position: new qq.maps.LatLng(lat,lng),
	        map: map
	    });
    });
    
    //实例化自动完成
    var ap = new qq.maps.place.Autocomplete(document.getElementById('address'));
    
    var keyword = "";
    //设置Poi检索服务，用于本地检索、周边检索
    searchService = new qq.maps.SearchService({
        //检索成功的回调函数
        complete: function(results) {
        	//console.log(results);
        	if(results.type === "CITY_LIST") {
                searchService.setLocation(results.detail.cities[0].cityName);
                keyword = $("#address").val();
                searchService.search(keyword);
                return;
            }
            //设置回调函数参数
            var pois = results.detail.pois;
            var infoWin = new qq.maps.InfoWindow({
                map: map
            });
            
            //地址位置是否存在
            if(pois == undefined){
            	alert("出错了，请输入正确的地址！！！");
            	return false;
            }
            
            var latlngBounds = new qq.maps.LatLngBounds();
            for (var i = 0, l = pois.length; i < l; i++) {
                var poi = pois[i];
                //扩展边界范围，用来包含搜索到的Poi点
                latlngBounds.extend(poi.latLng);
   
                (function(n) {
                    var marker = new qq.maps.Marker({
                        map: map
                    });
                    marker.setPosition(pois[n].latLng);
   
                    marker.setTitle(i + 1);
                    markers.push(marker);
   
                    qq.maps.event.addListener(marker, 'click', function() {
                        infoWin.open();
                        if(pois[n].address == undefined){
                        	var keywordAddress = document.getElementById("address").value;
                        	pois[n].address = keywordAddress;
                        }
                        //console.log(pois[n]);
                        lat = pois[n].latLng.lat;
				    	lng = pois[n].latLng.lng;
				    	detail = pois[n].address;
                        $("#address").val(pois[n].address);
                        $("#location").val(pois[n].address);
                        infoWin.setContent('<div style="width:280px;height:120px;">' + 'POI的名称为：' + pois[n].name + '<br>POI的地址为：' + pois[n].address + '</div>');
                        infoWin.setPosition(pois[n].latLng);
                        //根据经纬度获取地址
                        codeLatLng();
                    });
                })(i);
            }
            //调整地图视野
            map.fitBounds(latlngBounds);
        },
        //若服务请求失败，则运行以下函数
        error: function() {
            alert("出错了，请输入正确的地址！！！");
        }
    });
    
    //添加监听事件
    qq.maps.event.addListener(ap, "confirm", function(res){
    	//console.log(res);
        keyword = res.value;
        searchService.search(keyword);
    });

  
}

//搜索 地址 并获取经纬度
function codeAddress() {
    var address = document.getElementById("address").value;
    //对指定地址进行解析
    geocoder.getLocation(address);
    //设置服务请求成功的回调函数
    geocoder.setComplete(function(result) {
    	//console.log(result.detail,33333);
    	lat = result.detail.location.lat;
    	lng = result.detail.location.lng;
    	detail = result.detail.address;
    	$("#address").val(detail);
        map.setCenter(result.detail.location);
        marker.setMap(null);
        marker = new qq.maps.Marker({
            map: map,
            position: result.detail.location
        });
        //点击Marker会弹出反查结果
        qq.maps.event.addListener(marker, 'click', function() {
            alert("坐标地址为： " + result.detail.location);
        });
    });
    //若服务请求失败，则运行以下函数
    geocoder.setError(function(result) {
        alert("出错了，请输入正确的地址！！！");
    });
}
 
// 根据经纬度获取 地址
function codeLatLng() {
    var latLng = new qq.maps.LatLng(lat, lng);
    //对指定经纬度进行解析
    geocoder.getAddress(latLng);
    //设置服务请求成功的回调函数
    geocoder.setComplete(function(result) {
      	console.log(result,'88888888888888888888888888');
    	detail = result.detail.address;
      	$("#address").val(detail);
      	$("#location").val(detail);
      	$("#latitude").val(result.detail.location.lat);
      	$("#longitude").val(result.detail.location.lng);
    	//省市区
    	$("#province").val(result.detail.addressComponents.province);
    	$("#city").val(result.detail.addressComponents.city);
    	$("#district").val(result.detail.addressComponents.district);
//  	$("#address").val(result.detail.address);
    });
    //若服务请求失败，则运行以下函数
    geocoder.setError(function() {
        alert("出错了，请输入正确的经纬度！！！");
    });
}

//清除地图上的marker
function clearOverlays(overlays) {
    var overlay;
    while (overlay = overlays.pop()) {
        overlay.setMap(null);
    }
}

//设置搜索的范围和关键字等属性
function searchKeyword() {
    var keyword = document.getElementById("address").value;
    var region = '全国';//document.getElementById("region").value;
    //var pageIndex = parseInt(document.getElementById("pageIndex").value);
    //var pageCapacity = parseInt(document.getElementById("pageCapacity").value);
    clearOverlays(markers);
    //根据输入的城市设置搜索范围
    searchService.setLocation(region);
    //设置搜索页码
    //searchService.setPageIndex(pageIndex);
    //设置每页的结果数
    //searchService.setPageCapacity(pageCapacity);
    //根据输入的关键字在搜索范围内检索
    searchService.search(keyword);
    //根据输入的关键字在圆形范围内检索
    //var region = new qq.maps.LatLng(39.916527,116.397128);
    //searchService.searchNearBy(keyword, region , 2000);
    //根据输入的关键字在矩形范围内检索
    //region = new qq.maps.LatLngBounds(new qq.maps.LatLng(39.936273,116.440043),new qq.maps.LatLng(39.896775,116.354212));
    //searchService.searchInBounds(keyword, region);
}